# coding=utf-8
import MySQLdb

def db_connection(**kwargs):
    user = kwargs.get('user', 'root')
    password = kwargs.get('password', '')
    host = kwargs.get('host', '127.0.0.1')
    port = kwargs.get('port', '3306')
    db = kwargs.get('db', None)
    charset = kwargs.get('charset', 'utf8')

    conn = MySQLdb.connect(user=user, passwd=password, host=host, charset=charset)

    return conn

    
if __name__ == '__main__':
    conn = db_connection()
    cursor = conn.cursor()

    try:
        conn.select_db("test")
    except:
        cursor.execute("CREATE DATABASE IF NOT EXISTS test")
    try:
        cursor.execute("DROP TABLE IF EXISTS user")
        cursor.execute("CREATE TABLE IF NOT EXISTS user(id int(11) primary key,name char(64))")

        users = []
        for i in range(1, 11):
            users.append((i, "user%s" % i))
        cursor.executemany("insert into user values(%s,%s)",users)

        # for i in range(111, 211):
            # cursor.execute('insert into user values(%s, %s)' % (i, i))

        
        # 查询
        if cursor.execute("select * from user"): # if 会触发操作
            for row in cursor.fetchall():
                for r in row:
                    # print r
                    pass
        
        #删除
        sql = "delete from user where id=%s"
        param =("9")
        q =  cursor.execute(sql,param)
        print q
        
        conn.commit() # 提交
        cursor.close()
        conn.close()
    except MySQLdb.Error,e:
        print "Mysql Error %d: %s" % (e.args[0], e.args[1])